package handler

import (
	"Data-API-MCP/backend/internal/application/usecase"
	"Data-API-MCP/backend/internal/domain/entity"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// ConnectionHandler 连接处理器
type ConnectionHandler struct {
	connectionUseCase *usecase.ConnectionUseCase
}

// NewConnectionHandler 创建连接处理器
func NewConnectionHandler(connectionUseCase *usecase.ConnectionUseCase) *ConnectionHandler {
	return &ConnectionHandler{
		connectionUseCase: connectionUseCase,
	}
}

// RegisterRoutes 注册路由
func (h *ConnectionHandler) RegisterRoutes(router *gin.Engine) {
	connections := router.Group("/api/connections")
	{
		connections.POST("", h.CreateConnection)
		connections.PUT("/:id", h.UpdateConnection)
		connections.DELETE("/:id", h.DeleteConnection)
		connections.GET("/:id", h.GetConnection)
		connections.GET("", h.ListConnections)
		connections.POST("/test", h.TestConnection)
	}
}

// CreateConnection 创建连接
// @Summary 创建数据库连接
// @Description 创建新的数据库连接
// @Tags connections
// @Accept json
// @Produce json
// @Param connection body entity.Connection true "连接信息"
// @Success 201 {object} entity.Connection
// @Failure 400 {object} ErrorResponse
// @Router /api/connections [post]
func (h *ConnectionHandler) CreateConnection(c *gin.Context) {
	var connection entity.Connection
	if err := c.ShouldBindJSON(&connection); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
		return
	}

	if err := h.connectionUseCase.CreateConnection(c.Request.Context(), &connection); err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		return
	}

	c.JSON(http.StatusCreated, connection)
}

// UpdateConnection 更新连接
// @Summary 更新数据库连接
// @Description 更新现有的数据库连接
// @Tags connections
// @Accept json
// @Produce json
// @Param id path string true "连接ID"
// @Param connection body entity.Connection true "连接信息"
// @Success 200 {object} entity.Connection
// @Failure 400 {object} ErrorResponse
// @Router /api/connections/{id} [put]
func (h *ConnectionHandler) UpdateConnection(c *gin.Context) {
	id := c.Param("id")
	var connection entity.Connection
	if err := c.ShouldBindJSON(&connection); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
		return
	}

	connection.ID = id
	if err := h.connectionUseCase.UpdateConnection(c.Request.Context(), &connection); err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		return
	}

	c.JSON(http.StatusOK, connection)
}

// DeleteConnection 删除连接
// @Summary 删除数据库连接
// @Description 删除指定的数据库连接
// @Tags connections
// @Produce json
// @Param id path string true "连接ID"
// @Success 204 "No Content"
// @Failure 400 {object} ErrorResponse
// @Router /api/connections/{id} [delete]
func (h *ConnectionHandler) DeleteConnection(c *gin.Context) {
	id := c.Param("id")
	if err := h.connectionUseCase.DeleteConnection(c.Request.Context(), id); err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		return
	}

	c.Status(http.StatusNoContent)
}

// GetConnection 获取连接
// @Summary 获取数据库连接
// @Description 获取指定ID的数据库连接
// @Tags connections
// @Produce json
// @Param id path string true "连接ID"
// @Success 200 {object} entity.Connection
// @Failure 400 {object} ErrorResponse
// @Router /api/connections/{id} [get]
func (h *ConnectionHandler) GetConnection(c *gin.Context) {
	id := c.Param("id")
	connection, err := h.connectionUseCase.GetConnection(c.Request.Context(), id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		return
	}

	c.JSON(http.StatusOK, connection)
}

// ListConnections 获取连接列表
// @Summary 获取数据库连接列表
// @Description 获取所有数据库连接的列表
// @Tags connections
// @Produce json
// @Param offset query int false "偏移量"
// @Param limit query int false "限制数量"
// @Success 200 {array} entity.Connection
// @Failure 400 {object} ErrorResponse
// @Router /api/connections [get]
func (h *ConnectionHandler) ListConnections(c *gin.Context) {
	offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))

	connections, err := h.connectionUseCase.ListConnections(c.Request.Context(), offset, limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, ErrorResponse{Error: err.Error()})
		return
	}

	c.JSON(http.StatusOK, connections)
}

// TestConnection 测试连接
// @Summary 测试数据库连接
// @Description 测试数据库连接是否可用
// @Tags connections
// @Accept json
// @Produce json
// @Param connection body entity.Connection true "连接信息"
// @Success 200 {object} entity.ConnectionStatus
// @Failure 400 {object} ErrorResponse
// @Router /api/connections/test [post]
func (h *ConnectionHandler) TestConnection(c *gin.Context) {
	var connection entity.Connection
	if err := c.ShouldBindJSON(&connection); err != nil {
		c.JSON(http.StatusBadRequest, ErrorResponse{Error: err.Error()})
		return
	}

	if err := h.connectionUseCase.TestConnection(c.Request.Context(), &connection); err != nil {
		c.JSON(http.StatusOK, entity.ConnectionStatus{
			Status: "failed",
			Error:  err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, entity.ConnectionStatus{
		Status: "success",
	})
}

// ErrorResponse 错误响应
type ErrorResponse struct {
	Error string `json:"error"`
}
